<?php
class Comment_service extends CI_Model
{

    const COMMENT_PAGE_SIZE = 50;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->model('comment_model');
    }

    function createComment($create_data, &$err)
    {
        $must_colum = [
            'novel_id', 'user_id', 'content'
        ];

        foreach($must_colum as $key => $value)
        {
            if ( ! isset($create_data[$value]) || empty($create_data[$value]))
            {
                $err = [
                    'errorCode'     => PARAM_ERR,
                    'errorMessage'  => '参数异常',
                ];
                message_logger('error', sprintf('params error, params is %s', var_export($create_data, true)));
                return false;
            }
        }
        $insert_data = [
            'comment_id'    => $this->comment_model->getUuid(),
            'novel_id'      => $create_data['novel_id'],
            'user_id'       => $create_data['user_id'],
            'content'       => $create_data['content'],
            'add_time'      => time(),
        ];
        $res = $this->comment_model->insert($insert_data);
        return $res;
    }

    public function getCommentListByNovel($novel_id, $page, &$err)
    {
        if (empty($novel_id))
        {
            $err = [
                'errorCode'     => PARAM_ERR,
                'errorMessage'  => '参数异常',
            ];
            return false;
        }
        if (empty($page))
        {
            $page = 1;
        }
        $comment_list = $this->comment_model->findAll([
            'fields'    => 'user_id, content, like, add_time',
            'where'     => [
                'novel_id'      => $novel_id,
                'deleted'       => 'N',
            ],
            'order_by'  => [
                'add_time'  => 'desc',
            ],
            'limit'         => self::COMMENT_PAGE_SIZE,
            'offset'        => ($page - 1) * self::COMMENT_PAGE_SIZE,
        ]);
        if (empty($comment_list))
        {
            return $comment_list;
        }
        $this->_fillCommentUser($comment_list);
        return toCamelCaseKey($comment_list);
    }

    public function likeComment($comment_id, $novel_id, $user_id)
    {

    }

    private function _fillCommentUser(&$comment_list)
    {
        $user_ids = array_column($comment_list, 'user_id');
        $users = $this->user_model->findAll([
            'fields'        => 'user_name, headpic, user_id',
            'where_in'      => [
                'user_id'   => $user_ids,
            ]
        ]);
        $user_map = array_column($users, null, 'user_id');
        array_walk($comment_list, function(&$row) use ($user_map) {
            $user_id = $row['user_id'];
            $row['user_name'] = $user_map[$user_id]['user_name'] ?? '';
            $row['headpic'] = $user_map[$user_id]['headpic'] ?? '';
        });
    }
}
